import validate from "../../../utils/validate";
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: "",
    realName: "",
    mobile: ""
  },

  onLoad(options) {
    let id = options.id;
    if (id) {
      this.setData({
        id
      });
      wx.setNavigationBarTitle({
        title: "修改小工"
      });
      this.getData();
    }
  },

  getData() {
    wx.showLoading({
      title: "查询中..."
    });
    wx.$apis.getUserInfo(this.data.id).then((res) => {
      const { realName, mobile } = res.data;
      this.setData({
        realName,
        mobile
      });
    });
  },

  /**
   * 小工添加完成回来
   */
  toEmployee() {
    this.submit();
  },

  submit() {
    if (!this.data.realName) {
      return wx.showToast({
        title: "请输入姓名",
        icon: "error",
        duration: 1000
      });
    }

    if (!this.data.mobile) {
      return wx.showToast({
        title: "请输入手机号码",
        icon: "error",
        duration: 1000
      });
    }

    if (!validate.mobile(this.data.mobile)) {
      return wx.showToast({
        title: "请输入正确号码",
        icon: "error",
        duration: 1000
      });
    }

    let api = "addMarketUser";
    if (this.data.id) {
      api = "updateMarketUser";
    }

    wx.showLoading({
      title: "添加中..."
    });
    wx.$apis[api]({
      id: this.data.id ? this.data.id : undefined,
      companyId: app.globalData.userInfo.companyData.companyId,
      realName: this.data.realName,
      mobile: this.data.mobile,
      marketRoleIds: [3]
    }).then((res) => {
      wx.setStorage({
        key: "back",
        data: 1,
        success() {
          wx.navigateBack();
        }
      });
    });
  }
});
